//
//  HJPositioning.m
//  KaiChat
//
//  Created by lx on 2023/11/13.
//

#import "HJPositioning.h"
#import <CoreLocation/CoreLocation.h>


@interface HJPositioning ()<CLLocationManagerDelegate>

@property (strong, nonatomic) CLLocationManager *manager;
@property (nonatomic, assign) BOOL isPerform;


@end


@implementation HJPositioning

- (void)stop {
    [self.manager stopUpdatingLocation];
    self.manager = nil;
}

- (void)start {
    
    _isPerform = NO;
    dispatch_async_queue(^{
        
        if ([CLLocationManager locationServicesEnabled] == NO) {
            dispatch_async_main_queue(^{
                if ([self.delegate respondsToSelector:@selector(positioningFail:error:)]) {
                    [self.delegate positioningFail:self error:[NSError errorWithCode:-10010 errorReason:@"Cannot obtain the location permission"]];
                }
            });
            return;
        };
        
        
        dispatch_async_main_queue(^{
            CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
            if (kCLAuthorizationStatusDenied == status || kCLAuthorizationStatusRestricted == status) {
                if ([self.delegate respondsToSelector:@selector(positioningFail:error:)]) {
                    [self.delegate positioningFail:self error:[NSError errorWithCode:-10010 errorReason:@"Cannot obtain the location permission"]];
                }
                return;
            }
            
            if (kCLAuthorizationStatusNotDetermined == status) {
                [self.manager requestWhenInUseAuthorization];
            }
            
            [self.manager startUpdatingLocation];
        });
    });

    
}

#pragma mark - 必须实现的方法
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    if ([self.delegate respondsToSelector:@selector(positioningFail:error:)]) {
        [self.delegate positioningFail:self error:error];
    }

}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    if (kCLAuthorizationStatusDenied == status || kCLAuthorizationStatusRestricted == status) {
        return;
    }
    
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    
    CLLocation *currentLocation = locations.lastObject;
        
    CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
    
    [geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        [self stop];
        
        CLPlacemark *place = [placemarks lastObject];
        
        CLLocationCoordinate2D  converterLocation = currentLocation.coordinate;
        CLLocationDegrees latitude = converterLocation.latitude;
        CLLocationDegrees longitude = converterLocation.longitude;
        
        
        self.latitude = @(latitude).stringValue;
        self.longitude = @(longitude).stringValue;
        self.province = place.administrativeArea;//省
        self.city = place.locality;//市
        self.area = place.subLocality;//区
        self.place = place.name;
        self.subThoroughfare = place.subThoroughfare;//子街道
        
        HJTools.tool.longitude = self.latitude;
        HJTools.tool.longitude = self.longitude;

        NSMutableString *placeStr = [NSMutableString string];
        for (CLPlacemark *place in placemarks) {
            NSDictionary *loction = [place addressDictionary];
            for (id obj in loction[@"FormattedAddressLines"]) {
                if ([obj isKindOfClass:[NSString class]]) {
                    [placeStr appendString:obj];
                }
            }
        }
        
        self.detailedAddress = placeStr;
        if (self.isPerform == NO) {
            self.isPerform = YES;
        }
        
        dispatch_async_main_queue(^{
            if ([self.delegate respondsToSelector:@selector(positioningSucceed:)]) {
                [self.delegate positioningSucceed:self];
            }
        });
        
        NSLog(@"placeStr = %@", placeStr);
    }];
}

#pragma mark - Getter & Setter
- (CLLocationManager *)manager {
    if (!_manager) {
        _manager = [CLLocationManager new];
        _manager.delegate = self;
        _manager.desiredAccuracy = kCLLocationAccuracyBest;
    }
    return _manager;
}




@end
